package com.softoa.serviceImp;

import com.softoa.mapper.HistoryNewsMapper;
import com.softoa.mapper.NewsMapper;
import com.softoa.mapper.SessionMapper;
import com.softoa.pojo.*;
import com.softoa.service.ISessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service

public class SessionServiceImp implements ISessionService {
    /**
     * sessionservice实体类
     */
    @Autowired
    SessionMapper sessionMapper;
    @Autowired
    NewsMapper newsMapper;

    @Autowired
    HistoryNewsMapper historyNewsMapper;
    @Autowired
    UserServiceImp userServiceImp;
    @Override
    public int sessionInsert(Session session) {
        Date date=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        session.setSessionStartTime(Timestamp.valueOf(df.format(date)));
        session.setUnreadNumber(0);
        //session.setBothSidesId("103-456");//后期需要动态获取用户id以及目标id
        return sessionMapper.sessionInsert(session);
    }

    @Override
    public int sessionUpdate(Session session) {


        sessionMapper.sessionUpdate(session);
        newsMapper.newsUpdate(session);
        return 0;
    }

    @Override
    public List<Session> sessionSelectList(String userId) {
        return sessionMapper.sessionSelectList(userId);
    }

    @Override
    public Session sessionSelectOne(int sessionId) {
        return sessionMapper.sessionSelectOne(sessionId);
    }

    @Override
    public List<News> sessionSelectNews(News rule) {
        java.util.List<News> list=newsMapper.newsSelectList(rule);
        //list.sort(Comparator.comparing(News::getNewsSendTime).reversed());

        return list;
    }

    @Override
    public int sessionInsertNews(News news) {
        //News n=new News();
        /**
         * 当前对news赋值属于测试工作，实际应用起来只需要自动赋值时间与拆分S\A UserID
         */
        //news.setSessionId(session.getSessionId());
        news.setNewsFormat("txt");
        news.setNewsState("1");
        //news.setNewsText("测试文本");
        Date date=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        news.setNewsSendTime(Timestamp.valueOf(df.format(date)));
        //String sendstr=String.valueOf("102");//后改为登陆账户id

        newsMapper.newsInsert(news);
        return 0;
    }
    @Override
    public java.util.List<SessionInfo> sessionShow(int userId) {
        java.util.List<SessionInfo> sessionInfos = new ArrayList<SessionInfo>();
        String suid=String.valueOf(userId);
        java.util.List<Session> sessionList=this.sessionSelectList(String.valueOf(userId));
        java.util.List<Integer> uIds=new ArrayList<Integer>();
        for(Session sinlist: sessionList){
            String bothuser="";
            SessionInfo sessionInfo = new SessionInfo();
            String both=sinlist.getBothSidesId();
            //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! "+both);
            String[] twoid=both.split("-");
            if(twoid[0].equals(suid)){
                uIds.add(Integer.parseInt(twoid[1]));
                bothuser=twoid[1];
            }
            else{
                System.out.println(twoid[0]);
                uIds.add(Integer.parseInt(twoid[0]));
                bothuser=twoid[0];
            }

            User u = new User();
            u.setUserId(Integer.parseInt(bothuser));
            User user = userServiceImp.userSelectOne(u);
            sessionInfo.setUserId(user.getUserId());
            sessionInfo.setUserAvatar(user.getUserAvatar());
            sessionInfo.setUserName(user.getUserName());

            sessionInfo.setSessionId(sinlist.getSessionId());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sessionInfo.setSessionStartTime(df.format(sinlist.getSessionStartTime()));
            sessionInfo.setBothSidesId(sinlist.getBothSidesId());
            sessionInfo.setUnreadNumber(sinlist.getUnreadNumber());

            News news = new News();
            news.setSessionId(sinlist.getSessionId());
            List<News> newsList = this.sessionSelectNews(news);
            if(newsList.size()!=0){
                int len=newsList.size();
                sessionInfo.setNewsText(newsList.get(len-1).getNewsText());
                String newsTime = df.format(newsList.get(len-1).getNewsSendTime());
                Date now=new Date();
                int year= now.getYear();
                int month=now.getMonth();
                int day=now.getDate();
                String[] onetime=newsTime.split(" ");
                String[] twotime=onetime[0].split("-");
                String[] thirdtime=onetime[1].split(":");
                if(Integer.parseInt(twotime[0])-1900!=year){
                    String str=twotime[0]+"-"+twotime[1];
                    sessionInfo.setNewsSendTime(str);
                }
                else{
                    if(Integer.parseInt(twotime[1])+1!=month||Integer.parseInt(twotime[2])!=day){
                        String str=twotime[1]+"-"+twotime[2];
                        sessionInfo.setNewsSendTime(str);
                    }
                    else{
                        String str=thirdtime[0]+":"+thirdtime[1]+":"+thirdtime[2];
                        sessionInfo.setNewsSendTime(str);
                    }
                }
                int num = 0;
                for (News n : newsList) {
                    if (n.getNewsState().equals("1")&&n.getAcceptUserId()==userId) {
                        num += 1;
                    }
                }
                sinlist.setUnreadNumber(num);
                sessionMapper.sessionUpdate(sinlist);
                sessionInfo.setUnreadNumber(num);

            }
            else {
                sessionInfo.setNewsText("暂无消息");
                sessionInfo.setNewsSendTime(null);
                sessionInfo.setUnreadNumber(0);
            }

            sessionInfos.add(sessionInfo);


            //sessionInfo.setNewsSendTime(newsTime);




        }




    return sessionInfos;
    }
    @Override
    public java.util.List<Historynews> historyShow(Historynews historynews){
        return historyNewsMapper.historyNewsSelectList(historynews);
    };
}
